<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的博客</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
            line-height: 1.6;
        }

        header,
        footer {
            background: #35424a;
            color: #ffffff;
            text-align: center;
            padding: 20px 0;
        }

        nav {
            background-color: #35424a;
            padding: 15px 0;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        nav ul {
            list-style-type: none;
            padding: 0;
            margin: 0;
            display: flex;
            justify-content: center;
        }

        nav ul li {
            margin: 0 15px;
        }

        nav ul li a {
            color: #ffffff;
            text-decoration: none;
            transition: color 0.3s;
        }

        nav ul li a:hover {
            color: #ffcc00;
        }

        .container {
            display: flex;
            justify-content: center;
            width: 80%;
            margin: auto;
        }

        .sidebar {
            flex-basis: 200px;
            margin-right: 20px;
        }

        .main-content {
            flex: 3;
            margin-right: 20px;
        }

        article,
        aside,
        .comment-form,
        .comments {
            background: #ffffff;
            border-radius: 5px;
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #ddd;
        }

        h2,
        h3 {
            color: #333;
        }

        .meta {
            font-size: 0.9em;
            color: #777;
        }

        .login {
            float: right;
        }

        .comment-form textarea {
            width: 100%;
            height: 100px;
            margin-bottom: 10px;
        }

        .comment-form button {
            padding: 10px 20px;
            background-color: #35424a;
            color: #ffffff;
            border: none;
            cursor: pointer;
            border-radius: 5px;
        }

        .comments h3 {
            color: #35424a;
            border-bottom: 2px solid #35424a;
            padding-bottom: 10px;
        }

        .comments p {
            padding: 10px 0;
            margin: 0;
            border-bottom: 1px solid #f2f2f2;
        }

        .comments p:last-child {
            border-bottom: none;
        }

        .comments p span {
            font-weight: bold;
            color: #35424a;
        }

        .comment-item {
            position: relative;
            padding: 20px;
            margin: 10px 0;
            background: #ffffff;
            border: 1px solid #ddd;
        }

        .comment-item button {
            border: none;
            background: none;
            cursor: pointer;
        }

        .codehilite {
            padding: 0;
        }

        .hljs-ln-numbers {
            user-select: none;
            text-align: center;
            color: #ccc;
            border-right: 1px solid #CCC;
            vertical-align: top;
            padding-right: 5px;
        }

        .hljs-ln .hljs-ln-code {
            padding-left: 10px;
            white-space: pre;
        }
    </style>
</head>

<body>

    <header>
        <h1>欢迎来到我的博客</h1>
    </header>

    <nav>
        <ul>
            <li><a href="/">首页</a></li>
            <li><a href="/user">个人</a></li>
        </ul>
    </nav>

    <main class="container">
        <aside class="sidebar">
            <h2>文章目录</h2>
            <ul>
                <li>{{ article.toc_html | safe }}</li>
            </ul>
        </aside>

        <div class="main-content">
            <h2>文章内容</h2>
            <article id="article1">
                <h2>{{ article.title }}</h2>
                <p class="meta">作者: {{ article.author }} | 发布时间: {{ article.create_time }} | 分类：{{ article.classifier }} | 标签：
                    {% for tag in article.tag.all %}{{ tag.name }}{% if not forloop.last %}, {% endif %}{% endfor %}
                </p>
                <p>{{ article.body_html | safe }}</p>
            </article>

            {% if user.is_authenticated %}
            <div class="comment-form" aria-labelledby="comment-form-title">
                <h3 id="comment-form-title">发表评论</h3>
                <form method="POST" action="/submit_comment/{{ article.id }}/">
                    {% csrf_token %}
                    <textarea name="comment" placeholder="输入你的评论..." required></textarea>
                    <button type="submit">提交评论</button>
                </form>
            </div>
            {% else %}
            <p style="color: #3f4c5a; text-align: center;">请先<a href="/login/">登录</a>后再发表评论。</p>
            {% endif %}

            <div class="comments" aria-labelledby="comments-title">
                <h3 id="comments-title">评论 (<span id="comments-count">{{ comments.count }}</span>)</h3>
                <label for="sort-order">排序方式:</label>
                <select id="sort-order" onchange="sortComments(this.value)">
                    <option value="latest">一天内</option>
                    <option value="week">一周内</option>
                    <option value="author">按作者</option>
                </select>
                <div id="comments-list">
                    {% load custom_filters %}
                    {% for comment in comments %}
                    <div class="comment-item" id="comment-{{ comment.id }}">
                        <p style="margin: 0;">
{#                            <img src="{{ user.head_img.url }}" alt="{{ comment.user.username }}的头像" style="width: 30px; height: 30px; border-radius: 50%; margin-right: 5px; vertical-align: middle;">#}
                            <span>{{ comment.user.username }} {{ comment.create_time }} : <br /></span>{{ comment.text }}</p>
                        <div style="position: absolute; bottom: 10px; right: 10px;">
                            <button class="delete-button" onclick="deleteComment({{ comment.id }})">
                                <i class="fas fa-trash-alt"></i> 删除
                            </button>
                            <button class="like-button" onclick="likeComment({{ comment.id }})"
                                {% if comment.id in user_liked_comments %}disabled{% endif %}>
                                <i class="fas fa-thumbs-up"></i> 点赞 {{ comment.like_count }}
                            </button>
                        </div>
                    </div>
                    {% empty %}
                    <p>暂无评论</p>
                    {% endfor %}
                </div>
            </div>
        </div>
    </main>

    <script src="../static/js/script.js"></script>
    <script src="https://cdn.bootcss.com/highlight.js/9.15.8/highlight.min.js"></script>
    <script src="https://cdn.bootcss.com/highlightjs-line-numbers.js/2.7.0/highlightjs-line-numbers.min.js"></script>
    <script>
        hljs.initHighlightingOnLoad();
        hljs.initLineNumbersOnLoad();

        function deleteComment(commentId) {
            if (confirm('你确定要删除这条评论吗？')) {
                fetch(`/delete_comment/${commentId}/`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}'
                    }
                }).then(response => {
                    if (response.ok) {
                        document.getElementById(`comment-${commentId}`).remove();
                        const commentsCountElement = document.getElementById('comments-count');
                        commentsCountElement.textContent = parseInt(commentsCountElement.textContent) - 1;
                    } else {
                        alert('不能删除其他用户的评论！！！');
                    }
                });
            }
        }

        function likeComment(commentId) {
            fetch(`/like_comment/${commentId}/`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}'
                }
            }).then(response => {
                return response.json();
            }).then(data => {
                if (data.success) {
                    const likeButton = document.querySelector(`#comment-${commentId} .like-button`);
                    let currentCount = parseInt(likeButton.textContent.match(/\d+/)[0]);

                    if (data.message === '已取消点赞') {
                        likeButton.innerHTML = `<i class="fas fa-thumbs-up"></i> 点赞 ${currentCount - 1}`;
                    } else {
                        likeButton.innerHTML = `<i class="fas fa-thumbs-up"></i> 点赞 ${currentCount + 1}`;
                    }
                } else {
                    alert(data.message);
                }
            });
        }

        document.querySelector('.comment-form form').addEventListener('submit', function(event) {
            event.preventDefault(); // 防止默认提交行为
            const form = event.target;
            const formData = new FormData(form);

            fetch(form.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}'
                }
            }).then(response => {
                if (response.ok) {
                    alert('提交成功');
                    location.reload(); // 刷新页面
                } else {
                    alert('提交失败，请重试');
                    location.reload(); // 刷新页面
                }
            }).catch(error => {
                alert('提交失败，请重试');
                location.reload(); // 刷新页面
            });
        });

        // 备份原始评论
        const originalComments = Array.from(document.querySelectorAll('.comment-item'));
        function sortComments(order) {
            let comments = [...originalComments]; // 用备份的评论数组进行排序
            const commentsList = document.getElementById('comments-list');
            let visibleComments = [];
            switch (order) {
                case 'latest':
                    comments.sort((a, b) => new Date(b.querySelector('span').textContent) - new Date(a.querySelector('span').textContent));
                    visibleComments = comments;
                    break;
                case 'week':
                    const oneWeekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
                    visibleComments = comments.filter(comment => {
                        const commentDate = new Date(comment.querySelector('span').textContent);
                        return commentDate >= oneWeekAgo;
                    });
                    break;
                case 'author':
                    visibleComments = comments.sort((a, b) => a.querySelector('span').textContent.localeCompare(b.querySelector('span').textContent));
                    break;
            }
            // 清空当前评论列表
            commentsList.innerHTML = '';
            // 如果没有评论显示提示信息
            if (visibleComments.length === 0) {
                commentsList.innerHTML = '<p>没有找到评论</p>';
            } else {
                // 重新填充可见评论
                visibleComments.forEach(comment => commentsList.appendChild(comment));
            }
        }
    </script>

    <footer>
        <p>&copy; 2024 我的博客. 保留所有权利.</p>
    </footer>

</body>

</html>
